import socket
import threading

class HttpSocket(object):
    def __init__(self,duankou):
        server_socket = socket.socket()
        server_socket.bind(("",duankou))
        server_socket.listen()
        self.server_socket = server_socket

    def start(self):
        while True:
            new_socket, new_address = self.server_socket.accept()
            threading.Thread(target=self.func,args=(new_socket, new_address),daemon=True).start()

    @staticmethod
    def func(new_socket, new_address):
        print(f'客户端{str(new_address)}已上线')
        recv_data = new_socket.recv(4096)
        if not recv_data:
            print(f"客户端{str(new_address)}已下线")
            new_socket.close()
            return
        path_info = recv_data.decode().split(" ")[1]
        print("收到用户的资源请求路径是,", path_info)


        if path_info == "/":
            path_info = '/index.html'

        if path_info.endswith('.html'):
            env = {"PATH_INFO":path_info}
            import Application
            status, headers, response_body = Application.app(env)
            response_data = f"HTTP/1.1 {status}\r\n"
            for header in headers:
                response_data += "%s : %s\r\n" % header
            response_data += "\r\n"
            response_data += response_body
            new_socket.send(response_data.encode())
            new_socket.close()

        else:
            try:
                with open("static" + path_info, "rb") as file:
                    file_data = file.read()
                    http_data = 'HTTP/1.1 200 OK\r\nServer: PWS\r\n\r\n'.encode() + file_data
            except:
                with open("static/404.html","rb") as file:
                    file_data = file.read()
                    http_data = 'HTTP/1.1 404 Not Found\r\nServer: PWS\r\n\r\n'.encode() + file_data
            finally:
                new_socket.send(http_data)
                new_socket.close()




if __name__ == '__main__':
    httpsocket = HttpSocket(8080)
    httpsocket.start()